package com.ccl.iot.views;


import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ccl.iot.R;
import com.ccl.iot.dialogs.AddSubBLirDialog;
import com.ccl.iot.dialogs.HDCustomDialog;
import com.ccl.iot.dialogs.ModifyIconDialog;
import com.ccl.iot.privates.Invoker;
import com.ccl.iot.publics.Messager;
import com.ccl.iot.publics.UIUtils;
import com.hzy.tvmao.KookongSDK;
import com.hzy.tvmao.interf.IRequestResult;
import com.kookong.app.data.BrandList;
import com.kookong.app.data.RemoteList;
import com.kookong.app.data.StbList;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class SelectBrandView extends RelativeLayout {

    public static int STATE_NORMAL = 0;
    public static int STATE_SEARCH = 1;

    private EditText mEtSearch;
    private CharSortView mCsvChars;
    private ListView mLvBrands;
    private TextView mTvPopChar;
    private List<BrandList.Brand> mBrands;
    private List<BrandList.Brand> mSearchBrands;
    private BrandAdapter mBrandAdapter;
    private HashMap<String, List<BrandList.Brand>> mCategrayBrands;
    private int mCurrentState = STATE_NORMAL;
    private int mType;
    private String mDevName;

    private List<StbList.Stb> mStbs;

    private ModifyIconDialog.OnSelectChangeListener mOnSelectChangeListener;
    private AddSubBLirDialog.OnApplianceSelectListener mOnApplianceSelectListener;

    public SelectBrandView(Context context) {
        this(context, null);
    }

    public SelectBrandView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SelectBrandView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
        initData();
        initListener();
    }

    private CharSortView.CharChangeListener mCharChangeListener = new CharSortView.CharChangeListener() {
        @Override
        public void onSelected(String word, boolean fromChar) {
            mTvPopChar.setText(word);
            if (mTvPopChar.getVisibility() == View.VISIBLE) {
                mInvoker.cancel();
            } else {
                mTvPopChar.setVisibility(View.VISIBLE);
            }
            mInvoker.invoke();

            if (fromChar && mCategrayBrands != null && mCategrayBrands.size() > 0) {
                if (mCategrayBrands.containsKey(word)) {
                    List<BrandList.Brand> brands = mCategrayBrands.get(word);
                    BrandList.Brand brand = brands.get(0);
                    int index = mBrands.indexOf(brand);
                    mLvBrands.setSelection(index);
                }
            }
        }
    };

    private Runnable mShowTask = new Runnable() {
        @Override
        public void run() {
            mTvPopChar.setVisibility(View.GONE);
        }
    };

    private Invoker mInvoker = new Invoker("Show word task", 2000, new Invoker.InvokeListener() {
        @Override
        public void onInvoke() {
            UIUtils.postTaskSafely(mShowTask);
        }
    });

    public class SortComparator implements Comparator<BrandList.Brand> {
        @Override
        public int compare(BrandList.Brand lhs, BrandList.Brand rhs) {
            return lhs.initial.charAt(0) - rhs.initial.charAt(0);
        }
    }

    private void initView() {
        View.inflate(getContext(), R.layout.view_select_brand, this);
        mEtSearch = (EditText) findViewById(R.id.et_search_brand);
        mCsvChars = (CharSortView) findViewById(R.id.csv_chars);
        mLvBrands = (ListView) findViewById(R.id.lv_brand);
        mTvPopChar = (TextView) findViewById(R.id.tv_pop_char);
    }

    private void initData() {
        mBrandAdapter = new BrandAdapter();
        mLvBrands.setAdapter(mBrandAdapter);
    }

    private void initListener() {
        mCsvChars.setCharChangeListener(mCharChangeListener);
        mLvBrands.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (mBrands != null && mBrands.size() > 0 && (totalItemCount - firstVisibleItem - visibleItemCount) > 0) {
                    mCsvChars.setChars(mBrands.get(firstVisibleItem).initial);
                }
            }
        });

        mLvBrands.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mBrands != null && mBrands.size() > 0) {
                    final ProgressDialog progressDialog = new ProgressDialog(getContext(), ProgressDialog.THEME_DEVICE_DEFAULT_LIGHT);
                    progressDialog.show();
                    BrandList.Brand brand = mBrands.get(position);
                    KookongSDK.getAllRemoteIds(mType, brand.brandId, 0, 0, new IRequestResult<RemoteList>() {

                        @Override
                        public void onSuccess(String msg, RemoteList result) {
                            List<Integer> remoteids = result.rids;
                            progressDialog.cancel();

                            if (mOnSelectChangeListener != null) {
                                mOnSelectChangeListener.onSelectChange();
                            }

                            final HDCustomDialog dialog = new HDCustomDialog(getContext(), R.style.device_dialog_style_notitle);
                            TestIrView testIrView = new TestIrView(getContext());
                            testIrView.setData(mType, remoteids, new ModifyIconDialog.OnSelectChangeListener() {
                                @Override
                                public void onSelectChange() {
                                    dialog.cancel();
                                }
                            }, mDevName, mOnApplianceSelectListener);

                            dialog.setContentView(getContext().getResources().getString(R.string.control_select), testIrView);
                            dialog.show();
                        }

                        @Override
                        public void onFail(Integer errorCode, String msg) {
                            progressDialog.cancel();
                            Messager.Show(msg);
                            Log.e("getAllRemoteIds", "msg: " + msg + ", errorCode: " + errorCode);
                        }
                    });
                } else if (mStbs != null && mStbs.size() > 0) {
                    if (mOnSelectChangeListener != null) {
                        mOnSelectChangeListener.onSelectChange();
                    }
                    List<Integer> ids = new ArrayList<Integer>();
                    StbList.Stb stb = mStbs.get(position);
                    for (StbList.Remote remote : stb.remotes) {
                        ids.add(remote.rid);
                    }
                    final HDCustomDialog dialog = new HDCustomDialog(getContext(), R.style.device_dialog_style_notitle);
                    TestIrView testIrView = new TestIrView(getContext());
                    testIrView.setData(mType, ids, new ModifyIconDialog.OnSelectChangeListener() {
                        @Override
                        public void onSelectChange() {
                            dialog.cancel();
                        }
                    }, mDevName, mOnApplianceSelectListener);

                    dialog.setContentView(getContext().getResources().getString(R.string.control_select), testIrView);
                    dialog.show();
                }
            }
        });

        mEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    public void setBrands(List<BrandList.Brand> brands, int type, ModifyIconDialog.OnSelectChangeListener OnSelectChangeListener, String devName, AddSubBLirDialog.OnApplianceSelectListener listener) {
        mOnApplianceSelectListener = listener;
        mDevName = devName;
        mOnSelectChangeListener = OnSelectChangeListener;
        mType = type;
        mBrands = brands;
        Collections.sort(mBrands, new SortComparator());
        sortByBrands();
        mBrandAdapter.notifyDataSetChanged();
    }

    public void setStbBrands(List<StbList.Stb> stbs, int type, ModifyIconDialog.OnSelectChangeListener OnSelectChangeListener, String devName, AddSubBLirDialog.OnApplianceSelectListener listener) {
        mOnApplianceSelectListener = listener;
        mDevName = devName;
        mOnSelectChangeListener = OnSelectChangeListener;
        mType = type;
        mStbs = stbs;
        mCsvChars.setVisibility(View.GONE);
        mEtSearch.setVisibility(View.GONE);
        mBrandAdapter.notifyDataSetChanged();
    }

    private void sortByBrands() {
        if (mBrands != null && mBrands.size() > 0) {
            mCategrayBrands = new HashMap<>();
            for (int i = 0; i < mBrands.size(); i++) {
                BrandList.Brand brand = mBrands.get(i);
                if (mCategrayBrands.containsKey(brand.initial)) {
                    List<BrandList.Brand> brands = mCategrayBrands.get(brand.initial);
                    brands.add(brand);
                } else {
                    ArrayList<BrandList.Brand> brands = new ArrayList<>();
                    brands.add(brand);
                    mCategrayBrands.put(brand.initial, brands);
                }
            }

            Set<String> strings = mCategrayBrands.keySet();
            mCsvChars.setChars(strings.iterator().next());
        }
    }

    private class BrandAdapter extends BaseAdapter {
        private int mItemHeight;

        public BrandAdapter() {
            mItemHeight = UIUtils.dp2px(40);
        }

        @Override
        public int getCount() {
            if (mCurrentState == STATE_NORMAL) {
                if (mBrands != null && mBrands.size() > 0) {
                    return mBrands.size();
                }

                if (mStbs != null && mStbs.size() > 0) {
                    return mStbs.size();
                }
            } else if (mCurrentState == STATE_SEARCH) {
                if (mSearchBrands != null && mSearchBrands.size() > 0) {
                    return mSearchBrands.size();
                }
            }
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return mBrands.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                TextView tv = new TextView(getContext());
                tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mItemHeight));
                tv.setGravity(Gravity.CENTER_VERTICAL);
                tv.setTextColor(Color.BLACK);
                tv.setBackgroundResource(R.drawable.selector_back_btn);
                convertView = tv;
            }

            if (mBrands != null && mBrands.size() > 0) {
                ((TextView) convertView).setText(mBrands.get(position).cname);
            } else if (mStbs != null && mStbs.size() > 0) {
                ((TextView) convertView).setText(mStbs.get(position).bname);
            }

            return convertView;
        }
    }

}
